package com.microservice.skeleton.common.vo;

import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
import org.springframework.web.method.annotation.RequestHeaderMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

import java.util.Map;

/**
 * @author: lijin
 * @date: 2018年10月01日
 */
public class AccessTokenMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver {

    @Override
    protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
        RequestHeader annotation = parameter.getParameterAnnotation(RequestHeader.class);
        return new NamedValueInfo("Authorization", true, null);
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(AccessToken.class);
    }

    protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
        String[] headerValues = request.getHeaderValues(name);
        if (headerValues != null) {
                String headerValue = headerValues[0];
                headerValue = headerValue.substring(headerValue.indexOf(" ") + 1, headerValue.length());
                return  headerValue;
        }
        else {
            return null;
        }
    }
}
